package com.edu.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.edu.admin.entity.SysRole;
import com.edu.admin.enums.ExceptionEnum;
import com.edu.admin.service.RoleMenuService;
import com.edu.admin.service.RoleService;
import com.edu.admin.common.RestResult;
import com.edu.admin.vo.RoleMenuVo;
import com.edu.admin.vo.RoleVo;
import com.github.pagehelper.PageInfo;


/**
 * 平台级角色管理
 *  
 * @author Wangjiong
 * 
 */
@RestController
@RequestMapping(value = "/role", name = "平台级角色管理")
public class RoleController {
	
	@Autowired
	private RoleService	roleService;
	@Autowired
	private RoleMenuService	roleMenuService;

	/**
	 *
	 * @apiGroup role
	 * @api {get} /role/list 获取角色列表
	 * @apiVersion 1.0.0
	 * @apiName getRoleList
	 *
	 *
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		  {
		    "code": 200,
		    "msg": "success",
		    "data": [
		        {
		            "roleId": 1,
		            "roleName": "平台管理员",
		            "roleLevel": 1,
		            "useType": 0,
		            "menuIds": []
		        },
		        {
		            "roleId": 2,
		            "roleName": "学校管理员",
		            "roleLevel": 2,
		            "useType": 0,
		            "menuIds": []
		        },
		        {
		            "roleId": 3,
		            "roleName": "超级管理员",
		            "roleLevel": 0,
		            "useType": 0,
		            "menuIds": []
		        },
		        {
		            "roleId": 4,
		            "roleName": "管理员1",
		            "roleLevel": 1,
		            "useType": 0,
		            "menuIds": [
		                1,
		                2
		            ]
		        },
		        {
		            "roleId": 5,
		            "roleName": "管理员2",
		            "roleLevel": 1,
		            "useType": 0,
		            "menuIds": []
		        }
		    ]
		}
	 *
	 *
	 */
    @RequestMapping(value = "list", name = "可用角色列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/role/list')")
    public RestResult getRoleList() throws Exception {

        List<RoleVo> roleList = roleService.getRoleList();
        return RestResult.ok(roleList);
    }
    
    /**
	 *
	 * @apiGroup role
	 * @api {get} /role/listAll 获取所有角色列表（包括停用角色）
	 * @apiVersion 1.0.0
	 * @apiName getAllRoleList
	 *
	 *
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		  {
		    "code": 200,
		    "msg": "success",
		    "data": [
		        {
		            "roleId": 1,
		            "roleName": "平台管理员",
		            "roleLevel": 1,
		            "useType": 0,
		            "menuIds": []
		        },
		        {
		            "roleId": 2,
		            "roleName": "学校管理员",
		            "roleLevel": 2,
		            "useType": 0,
		            "menuIds": []
		        }
		    ]
		}
	 *
	 *
	 */
    @RequestMapping(value = "listAll", name = "所有角色列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/role/listAll')")
    public RestResult getAllRoleList() throws Exception {

        List<RoleVo> roleList = roleService.getAllRoleList();
        return RestResult.ok(roleList);
    }
    
    /**
   	 *
   	 * @apiGroup role
   	 * @api {get} /role/listAllPage 获取所有角色列表（包括停用角色）（分页显示）
   	 * @apiVersion 1.0.0
   	 * @apiName getAllRoleListPage
   	 *
   	 * @apiParam {Integer} pageNum 页码  required = false
   	 * @apiParam {Integer} pageSize 每页行数  required = false
   	 *
   	 * @apiSuccessExample Success-Response:
   	 * HTTP/1.1 200
		   {
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "total": 3,
		        "list": [
		            {
		                "roleId": 1,
		                "roleName": "平台管理员",
		                "roleLevel": 1,
		                "useType": 0,
		                "menuIds": []
		            },
		            {
		                "roleId": 2,
		                "roleName": "学校管理员",
		                "roleLevel": 2,
		                "useType": 0,
		                "menuIds": []
		            },
		            {
		                "roleId": 3,
		                "roleName": "超级管理员",
		                "roleLevel": 0,
		                "useType": 0,
		                "menuIds": []
		            }
		        ],
		        "pageNum": 1,
		        "pageSize": 10,
		        "size": 3,
		        "startRow": 1,
		        "endRow": 3,
		        "pages": 1,
		        "prePage": 0,
		        "nextPage": 0,
		        "isFirstPage": true,
		        "isLastPage": true,
		        "hasPreviousPage": false,
		        "hasNextPage": false,
		        "navigatePages": 8,
		        "navigatepageNums": [
		            1
		        ],
		        "navigateFirstPage": 1,
		        "navigateLastPage": 1,
		        "lastPage": 1,
		        "firstPage": 1
		    }
		}
   	 *
   	 *
   	 */
    @RequestMapping(value = "listAllPage", name = "角色列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/role/listAllPage')")
    public RestResult getAllRoleListPage(@RequestParam(name = "pageNum", required = false) Integer pageNum,
			@RequestParam(name = "pageSize", required = false) Integer pageSize) 
			throws Exception {

		PageInfo<RoleVo> pageInfo = roleService.getAllRoleListPage(pageNum,pageSize);
        return RestResult.ok(pageInfo);
    }
    
    /**
 	 *
 	 * @apiGroup role
 	 * @api {post} /role/save 保存角色信息
 	 * @apiVersion 1.0.0
 	 * @apiName save
 	 *
 	 * @apiParam {SysRole} role 角色信息
 	 * @apiParamExample 请求示例（json）
 	 * {
		  "roleName":"学校管理员",
		  "roleLevel": 2
		
		} 
 	 *
 	 * @apiSuccessExample Success-Response:
 	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "roleId": 3
		    }
		}
 	 *
 	 *
 	 */
	@RequestMapping(value = "save", name = "保存角色信息", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/role/save')")
	public RestResult save(@Valid @RequestBody SysRole role) throws Exception{
		Map<String, Object> result = new HashMap<>();
				
		result = roleService.saveRole(role);
	
		return RestResult.ok(result);
	}
	
	/**
	 *
	 * @apiGroup role
	 * @api {get} /role/info 获取角色信息
	 * @apiVersion 1.0.0
	 * @apiName getRole
	 *
	 * @apiParam {Long} roleId 角色id
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "roleId": 2,
		        "roleName": "学校管理员",
		        "roleLevel": 2,
		        "useType": 0,
		        "menuIds": []
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "info", name = "角色信息", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('/role/info')")
	public RestResult getRole(@RequestParam Long roleId) throws Exception{

		RoleVo roleVo = roleService.getRole(roleId);

		return RestResult.ok(roleVo);
	}
	
	/**
	 *
	 * @apiGroup role
	 * @api {post} /role/delete 删除角色
	 * @apiVersion 1.0.0
	 * @apiName deleteRole
	 *
	 * @apiParam Map<String,Object> paramMap
	 * @apiParamExample 请求示例（json）
  	 * {
		  "roleId":"1"
		
		} 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
   @RequestMapping(value="/delete" , method = RequestMethod.POST)
   @PreAuthorize("hasAuthority('/role/delete')")
   public RestResult deleteRole(@RequestBody Map<String,Object> dataMap) throws Exception {
 	   
		Long roleId = MapUtils.getLong(dataMap, "roleId");
		
		if (roleId == null || roleId<=0)
		{
			return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
		}
	   	    			
	   	int isOk = roleService.deleteRole(roleId);
	   	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
   }
   
   /**
	 *
	 * @apiGroup role
	 * @api {post} /role/on 启用角色
	 * @apiVersion 1.0.0
	 * @apiName onRole
	 *
	 * @apiParam Map<String,Object> paramMap
	 * @apiParamExample 请求示例（json）
  	 * {
		  "roleId":"1"
		
		} 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
   @RequestMapping(value="/on" , method = RequestMethod.POST)
   @PreAuthorize("hasAuthority('/role/on')")
   public RestResult onRole(@RequestBody Map<String,Object> dataMap) throws Exception {
 	   
		Long roleId = MapUtils.getLong(dataMap, "roleId");
		
		if (roleId == null || roleId<=0)
		{
			return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
		}
   	    			
	   	int isOk = roleService.useRole(roleId,0);
	   	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
   }
   
   /**
	 *
	 * @apiGroup role
	 * @api {post} /role/off 停用角色
	 * @apiVersion 1.0.0
	 * @apiName offRole
	 *
	 * @apiParam Map<String,Object> paramMap
	 * @apiParamExample 请求示例（json）
  	 * {
		  "roleId":"1"
		
		} 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
   @RequestMapping(value="/off" , method = RequestMethod.POST)
   @PreAuthorize("hasAuthority('/role/off')")
   public RestResult offRole(@RequestBody Map<String,Object> dataMap) throws Exception {
 	   
		Long roleId = MapUtils.getLong(dataMap, "roleId");
		
		if (roleId == null || roleId<=0)
		{
			return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
		}
   	    			
	   	int isOk = roleService.useRole(roleId,1);
	   	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
   }
   
   /**
	 *
	 * @apiGroup role
	 * @api {get} /role/saveRoleMenu 删除角色
	 * @apiVersion 1.0.0
	 * @apiName saveRoleMenu
	 *
	 * @apiParam Map<String,Object> paramMap
	 * @apiParamExample 请求示例（json）
  	 * {
		  "roleId":"1",
		  "menuIds":[1,2,3,4]
		
		} 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
   @RequestMapping(value = "saveRoleMenu", name = "保存角色权限", method = RequestMethod.POST)
   @PreAuthorize("hasAuthority('/role/saveRoleMenu')")
   public RestResult saveRoleMenu(@RequestBody Map<String,Object> paramMap) 
			throws Exception {
	   Long roleId = MapUtils.getLong(paramMap,"roleId");
       @SuppressWarnings("unchecked")
	List<Integer> menuIds = (List<Integer>)MapUtils.getObject(paramMap,"menuIds");
       Integer[] ids = new Integer[]{};
       if(menuIds != null){
           ids = new Integer[menuIds.size()];
           menuIds.toArray(ids);
       }
	   roleMenuService.saveRoleMenu(roleId,ids);
       return RestResult.ok();
   }
   
   /**
	 * 角色菜单列表
	 *
	 * @apiGroup role
	 * @api {get} /role/menulist 角色菜单列表
	 * @apiVersion 1.0.0
	 * @apiName getRoleMenuList
	 *
	 * @apiParam Long roleId
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200 
		{
		    "code": 200,
		    "msg": "success",
		    "data": [
		        {
		            "roleId": 2,
		            "menuId": 4,
		            "roleName": "平台管理员",
		            "menuName": "管理员管理"
		        }
		    ]
		}
   * 
   */
  @RequestMapping(value = "menulist", name = "角色菜单列表", method = RequestMethod.GET)
  @PreAuthorize("hasAuthority('/role/menulist')")
  public RestResult getRoleMenuList(Long roleId) throws Exception {

      List<RoleMenuVo> roleMenuList = roleMenuService.getRoleMenuListByRoleId(roleId);
      return RestResult.ok(roleMenuList);
  }
	


}
